//
//  TMGFlowViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/13.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGMonthPlanViewController.h"
#import "TMMenuControl.h"
#import "TMGUserTableViewCell.h"
#import "TMGFlowMoreTableViewCell.h"
#import "TMGBuyGoldViewController.h"
#import "NSCalendar+STCalendarTool.h"
@interface TMGMonthPlanViewController ()
@property(nonatomic, strong) NSArray                               *titleArray;
@property(nonatomic, strong) STSegementButton                      *segementButton;
@property(nonatomic, strong) UIView                                *topView;
@property(nonatomic, strong) NSArray<STTableEasyModel*>            *productArray;
@property(nonatomic, strong) NSMutableArray                               *userArray;
@property(nonatomic, strong) NSArray                               *moreArray;
@property(nonatomic, strong) TMGProductDetailModel                     *detailModel;
@end

@implementation TMGMonthPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.model.name;
    _titleArray = @[@"产品详情",@"购买人数"];
    [self configSubView];
    [self configBootomView];
    [self configTableHeader];
    [self configTableFooter];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (IOS11 && [self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.tableView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.tableView.frame = CGRectMake(0, self.topView.bottom, UIScreenWidth, UIScreenHeight - 50 - self.topView.bottom);
    [self.tableView registerClass:[TMGUserTableViewCell class] forCellReuseIdentifier:@"userCell"];
    //[self.tableView registerClass:[TMGFlowMoreTableViewCell class] forCellReuseIdentifier:@"moreCell"];
    [self sendGoodDetailReqeust];
    [self sendGoodPeopleBuyReqeust];
    // Do any additional setup after loading the view.
}
- (void)reloadData{
    NSString * free = [NSString stringWithFormat:@"%@元/克",self.detailModel.fee];
    
    NSString * saleFree = [NSString stringWithFormat:@"%@元/克",self.detailModel.fee_sale];
    
    NSString * rate = self.detailModel.year_rate_from;
    if (self.detailModel.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.detailModel.year_rate_from,self.detailModel.year_rate_to];
    }
    rate = [NSString stringWithFormat:@"%@%%",rate];
    
    NSDate * date = [NSDate date].st_localDate;
    
    self.productArray = @[
                          [[STTableEasyModel alloc] initWithTextString:@"产品介绍" detailString:@""],
                          [[STTableEasyModel alloc] initWithTextString:@"产品说明" detailString:@"投资期间不可转让，赎回"],
                          [[STTableEasyModel alloc] initWithTextString:@"手续费"
                                                          detailString:free],
                          [[STTableEasyModel alloc] initWithTextString:@"买入期限"
                                                          detailString:@""],
                          [[STTableEasyModel alloc] initWithTextString:@"风险等级" detailString:@"稳健性"],
                          [[STTableEasyModel alloc] initWithTextString:@"预计黄金收益率"
                                                          detailString:rate],
                          [[STTableEasyModel alloc] initWithTextString:@"购买截止"
                                                          detailString:self.detailModel.deadline],
                          [[STTableEasyModel alloc] initWithTextString:@"计息开始日"
                                                          detailString:@"T+1"],
                          [[STTableEasyModel alloc] initWithTextString:@"计息结束日"
                                                          detailString:@""],
                          [[STTableEasyModel alloc] initWithTextString:@"收益发放日"
                                                          detailString:@"T+2"],
                          [[STTableEasyModel alloc] initWithTextString:@"收益发放方式" detailString:@"一次性还本利息 "],
                          [[STTableEasyModel alloc] initWithTextString:@"计息期"
                                                          detailString:[NSString stringWithFormat:@"%@月",self.detailModel.day_number]],
                          [[STTableEasyModel alloc] initWithTextString:@"单词购买上限"
                                                          detailString:self.detailModel.buy_limit],
                          [[STTableEasyModel alloc] initWithTextString:@"起购金额"
                                                          detailString:@(self.detailModel.buy_start.integerValue).description],
                          ];
    
    self.moreArray = @[@"",@"",@""];
    [self.tableView reloadData];
    [self configTableHeader];
    [self configTableFooter];
}
- (void)configDataSouce{
    
    self.productArray = @[
                          [[STTableEasyModel alloc] initWithTextString:@"产品介绍" detailString:@""],
                          [[STTableEasyModel alloc] initWithTextString:@"产品说明" detailString:@"投资期间不可转让，赎回"],
                          [[STTableEasyModel alloc] initWithTextString:@"手续费" detailString:@"0元"],
                          [[STTableEasyModel alloc] initWithTextString:@"买入期限" detailString:@"每笔0.3/克"],
                          [[STTableEasyModel alloc] initWithTextString:@"风险等级" detailString:@"稳健性"],
                          [[STTableEasyModel alloc] initWithTextString:@"预计黄金收益率" detailString:@"7%"],
                          [[STTableEasyModel alloc] initWithTextString:@"购买截止" detailString:@"2017-12-11"],
                          [[STTableEasyModel alloc] initWithTextString:@"计息开始日" detailString:@"2017-12-12"],
                          [[STTableEasyModel alloc] initWithTextString:@"计息结束日" detailString:@"2018-1-11"],
                          [[STTableEasyModel alloc] initWithTextString:@"收益发放日" detailString:@"2018-1-12"],
                          [[STTableEasyModel alloc] initWithTextString:@"收益发放方式" detailString:@"一次性还本利息 "],
                          [[STTableEasyModel alloc] initWithTextString:@"计息期" detailString:@"30天"],
                          [[STTableEasyModel alloc] initWithTextString:@"单词购买上限" detailString:@"1000元"],
                          [[STTableEasyModel alloc] initWithTextString:@"起购金额" detailString:@"100元"],
                          ];
    
    self.userArray = @[@"",@"",@"",@"",@""];
    self.moreArray = @[@"",@"",@""];
}
#pragma mark --subView
- (void)configTableHeader{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 200)];
    header.backgroundColor = [UIColor whiteColor];
    
    NSString * rate = self.detailModel.year_rate_from;
    if (self.detailModel.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.detailModel.year_rate_from,self.detailModel.year_rate_to];
    }
    rate = [NSString stringWithFormat:@"%@%%",rate];
    
    UIView * product = [self headerWithTitle:@"产品简介"
                                         des:[NSString stringWithFormat:@"月月生息是黄金口袋推出的高安全系数高流动性的产品，投资次日开始计息，每日收益自动复投，复合预计黄金收益率高达%@",rate]];
    [header addSubview:product];
    
    UIView * winMethod = [self headerWithTitle:@"收益计算方法" des:@"月月生息的收益按日自动复投，即每日收益会加入本金中，用来计算次日的收益。由于收益复投得到的复合预计黄金收益率会比单日预计黄金收益率略高一些"];
    winMethod.top = product.bottom;
    [header addSubview:winMethod];
    
    UIView * buyCircle = [self headerWithTitle:@"赎回流程" des:@"黄金口袋会接到您提交的赎回申请后，盖币赎回资金会进入冻结中，当其他用户购买产品的累计金额大于或等于您的赎回金额后，则赎回成功，系统将该笔资金发放至您的账户余额"];
    buyCircle.top = winMethod.bottom;
    [header addSubview:buyCircle];
    
    header.height = buyCircle.bottom;
    self.tableView.tableHeaderView = header;
}
- (UIView*)headerWithTitle:(NSString*)title des:(NSString*)desStr{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 200)];
    header.backgroundColor = [UIColor whiteColor];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 20, 300, 20)
                                                     text:title
                                                textColor:TM_secendTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [header addSubview:titleLable];
    
    
    STLabel * desLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 15, 0.66 * UIScreenWidth, 20)
                                                   text:desStr
                                              textColor:TM_firstTextColor
                                                   font:14
                                            isSizetoFit:NO
                                          textAlignment:NSTextAlignmentLeft];
    desLable.right = UIScreenWidth - self.insetX;
    [header addSubview:desLable];
    [NSString lableAutoAdjustheightWithLabel:desLable];
    header.height = desLable.bottom  +15;
    [header st_showBottomLine];
    return header;
}
- (void)configTableFooter{
    
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    
    UIView  *comeForm = [self headerWithTitle:@"收益来源" des:@"您投资的资金将于购买知名平台的，安全性极高的债券，您的收益来自于债券产生的收益"];
    [footer addSubview:comeForm];
    comeForm.top = 10;
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, comeForm.bottom + 10, UIScreenWidth, 44)
                                                     text:[NSString stringWithFormat:@"剩余可购买金额%@元",
                                                           self.detailModel.is_sell]
                                                textColor:TM_secendTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    [footer addSubview:titleLable];
    footer.height = titleLable.bottom  + 10;
    self.tableView.tableFooterView = footer;
}
- (void)configSubView{
    
    UIView * topView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, UIScreenWidth, 100)];
    topView.backgroundColor = [UIColor whiteColor];
    UIImageView * bannerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    [self.view addSubview:topView];
    bannerImageView.backgroundColor = TM_orangeColor;
    bannerImageView.userInteractionEnabled = YES;
    [topView addSubview:bannerImageView];
    
    NSString * rate = self.detailModel.year_rate_from;
    if (self.detailModel.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.detailModel.year_rate_from,self.detailModel.year_rate_to];
    }
    rate = [NSString stringWithFormat:@"%@%%",rate];
    
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 10, 200, 80)
                                                     text:[NSString stringWithFormat:@"%@\n预计黄金收益率",rate]
                                                textColor:[UIColor whiteColor]
                                                     font:26
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    titleLable.centerX = UIScreenWidth / 2;
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:@"预计黄金收益率" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    [bannerImageView addSubview:titleLable];
    TMMenuControl *  suishiControl = [self controlWithValue:@"每月本息复投" name:@"计息方式 "];
    suishiControl.left = 0;
    suishiControl.top = bannerImageView.bottom;
    [topView addSubview:suishiControl];
    
    TMMenuControl *  baobenControl = [self controlWithValue:@"2000万" name:@"发售总额"];
    baobenControl.left = suishiControl.right;
    baobenControl.top = bannerImageView.bottom;
    [NSString lableAutoAdjustWitdhWithLabel:baobenControl.nameLable];
    baobenControl.nameLable.centerX = baobenControl.width / 2;
//    UIImageView * why = [[UIImageView alloc] initWithFrame:CGRectMake(baobenControl.nameLable.right + 10, baobenControl.nameLable.top, 10, 10)];
//    why.image = [UIImage imageNamed:@"问号"];
//    why.centerY = baobenControl.nameLable.centerY;
//    [baobenControl addSubview:why];
    [topView addSubview:baobenControl];
    
    TMMenuControl *  buyControl = [self controlWithValue:@(self.detailModel.buy_start.integerValue).description name:@"起购金额"];
    buyControl.left = baobenControl.right;
    buyControl.top = bannerImageView.bottom;
    [topView addSubview:buyControl];
    
    UIView * grawView = [[UIView alloc] initWithFrame:CGRectMake(0, buyControl.bottom, UIScreenWidth, 10)];
    grawView.backgroundColor = TM_backgroundColor;
    [topView addSubview:grawView];
    
    NSDate * date = [NSDate date].st_localDate;
    TMMenuControl *  beginControl = [self controlWithValue:@"开始计息"
                                                      name:[NSCalendar st_nextDayDate:date].st_yyyyMMddByLineWithDate];
    beginControl.left = 0;
    beginControl.top = grawView.bottom;
    [topView addSubview:beginControl];
    
    
    TMMenuControl *  meiyueControl = [self controlWithValue:@"每月加息续投" name:@"每月可预约赎回"];
    meiyueControl.left = beginControl.right;
    meiyueControl.top = grawView.bottom;
    [topView addSubview:meiyueControl];
    NSDate * deadLine = [date copy];
    for (NSInteger i =0 ; i < self.detailModel.day_number.integerValue; i ++) {
        deadLine = [NSCalendar st_nextMonthDate:deadLine];
    }
    NSString * finsh = deadLine.st_yyyyMMByLineWithDate;
    NSString * day = [[NSCalendar st_nextDayDate:date].st_yyyyMMddByLineWithDate componentsSeparatedByString:@"-"].lastObject;
    TMMenuControl *  daoqiControl = [self controlWithValue:@"到期退出"
                                                      name:[NSString stringWithFormat:@"%@-%@",finsh,day]];
    daoqiControl.left = meiyueControl.right;
    daoqiControl.top = grawView.bottom;
    [topView addSubview:daoqiControl];
    
    UIView * grawView1 = [[UIView alloc] initWithFrame:CGRectMake(0, daoqiControl.bottom, UIScreenWidth, 10)];
    grawView1.backgroundColor = TM_backgroundColor;
    [topView addSubview:grawView1];
    
    __weak typeof(self) weakSelf =  self;
    self.segementButton = [[STSegementButton alloc] initWithFrame:CGRectMake(0, grawView1.bottom, UIScreenWidth, 59)
                                                         andTitle:_titleArray handle:^(STSegementButton *sender) {
                                                             if (sender.tag == 0) {
                                                                 [weakSelf configTableHeader];
                                                                 [weakSelf configTableFooter];
                                                             }else{
                                                                 weakSelf.tableView.tableHeaderView = nil;
                                                                 weakSelf.tableView.tableFooterView = nil;
                                                             }
                                                             [weakSelf.tableView reloadData];
                                                         }];
    self.segementButton.backgroundColor = [UIColor whiteColor];
    self.segementButton.lineSelectedColor = TM_orangeColor;
    self.segementButton.butTitleSelectedColor = TM_orangeColor;
    self.segementButton.butTitleColor = TM_secendTextColor;
    self.segementButton.lineColor = [UIColor whiteColor];
    self.segementButton.cureentIndex = 0;
    self.segementButton.autoMoveWithClic = YES;
    [topView addSubview:self.segementButton];
    [TMGProductDataController sendPeopleAllNumWithGid:self.model.goodiID.description handle:^(NSString *num) {
        if (num.description.length) {
            UIButton * button = [self.segementButton buttonWirhIndex:1];
            [button setTitle:[NSString stringWithFormat:@"购买人数%@位",num] forState:UIControlStateNormal];
            [button setTitle:[NSString stringWithFormat:@"购买人数%@位",num] forState:UIControlStateSelected];
        }
    }];
    
    self.topView = topView;
    topView.height = self.segementButton.bottom;
    
}
- (TMMenuControl*)controlWithValue:(NSString*)value name:(NSString*)name{
    TMMenuControl * suishiControl = [[TMMenuControl alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth / 3, 60) value:@"随时买卖" name:@"买入期限" showLine:YES];
    [suishiControl addTarget:self action:@selector(onSlectedControl:) forControlEvents:UIControlEventTouchUpInside];
    suishiControl.valueLable.attributedText = nil;
    suishiControl.valueLable.text = value;
    suishiControl.nameLable.textColor = TM_secendTextColor;
    suishiControl.nameLable.text = name;
    return suishiControl;
}
- (void)configBootomView{
    __weak typeof(self) weakSelf =  self;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 50)
                                                     title:@"立即购买"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:TM_orangeColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedBuyButton];
    }];
    [self.view addSubview:buyButton];
    buyButton.bottom = UIScreenHeight;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.segementButton.cureentIndex == 0) {
        return self.productArray.count;
    }
    if (self.segementButton.cureentIndex == 1) {
        return self.userArray.count;
    }
    if (self.segementButton.cureentIndex == 2) {
        return self.moreArray.count;
    }
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segementButton.cureentIndex == 3) {
        return [TMGFlowMoreTableViewCell cellHeight];
    }
    if (self.segementButton.cureentIndex == 2) {
        return [TMGFlowMoreTableViewCell cellHeight];
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.segementButton.cureentIndex == 0) {
        static NSString * reuseIdentifier =  @"cell";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
            
        }
        cell.textLabel.textColor = TM_secendTextColor;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        cell.detailTextLabel.textColor = TM_firstTextColor;
        STTableEasyModel * model = self.productArray[indexPath.row];
        cell.textLabel.text = model.textString;
        cell.detailTextLabel.text = model.detailString;
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    if (self.segementButton.cureentIndex == 1) {
        TMGUserTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"userCell"];
        return cell;
    }
    if (self.segementButton.cureentIndex == 2) {
        TMGFlowMoreTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"moreCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    return nil;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSlectedControl:(TMMenuControl*)sender{
    
}
- (void)onSlectedBuyButton{
    TMGBuyGoldViewController * vc = [[TMGBuyGoldViewController alloc] initWithGoldType:TMGBuyGoldTypeGreenHand];
    vc.model = self.detailModel;
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark --NetWork Method
- (void)sendGoodDetailReqeust{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/goods/getGoodsDetails"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (self.model.goodiID.description.length) {
        [dic setObject:self.model.goodiID forKey:@"gid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.detailModel = [TMGProductDetailModel mj_objectWithKeyValues:dataDic];
                                                  self.detailModel.cate = self.model.cate.description;
                                                 [self configSubView];
                                                 [self configTableFooter];
                                                 [self reloadData];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendGoodPeopleBuyReqeust{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/goods/buyGoodsNumbers"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (self.model.goodiID.description.length) {
        [dic setObject:self.model.goodiID forKey:@"gid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.userArray = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in array) {
                                                     TMGBuyUserModel * model = [TMGBuyUserModel mj_objectWithKeyValues:modelDic];
                                                     [self.userArray addObject:model];
                                                 }
                                                 if (self.detailModel) {
                                                     [self reloadData];
                                                 }
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end


